package com.example.demo.consumer;


import com.example.demo.bean.Account;
import com.example.demo.bean.Order;
import com.example.demo.exception.AccountNotExistedException;
import com.example.demo.service.AccountService;
import com.example.demo.task.TransferTask;
import com.example.demo.untils.RedisUtil;
import com.github.phantomthief.pool.KeyAffinityExecutor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RocketMQMessageListener(topic = "commonAccount",consumerGroup = "order-consumer-group")
public class CommonAccountConsumer implements RocketMQListener<Order> {


    @Autowired
    private AccountService accountService;

    @Autowired
    RedisUtil redisUtil;
    //亲缘线程池
    KeyAffinityExecutor executor =
            KeyAffinityExecutor.newSerializingExecutor(8, 200, "MY-POOL");


    @SneakyThrows
    @Override
    public void onMessage(Order order) {
        boolean exists = redisUtil.set("orderId" + order.getOrderId(),1,1000, TimeUnit.SECONDS);
        if(exists){
            //订单相同
            return;
        }
        Account fromAccount = accountService.getById(order.getMerchantId());
        if(fromAccount == null) throw new AccountNotExistedException(order.getMerchantId());

        Double money = order.getMoney();
        String orderId = order.getOrderId();
        //创建转账任务
        TransferTask task = new TransferTask(fromAccount,money,orderId,true);
        executor.executeEx(order.getMerchantId(),task);
    }

}
